package com.sad.we11cis;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import android.R.anim;
import android.media.Image;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore.Images;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

public class ProductRegister extends Activity implements OnClickListener {

	private final int RECEIVE_TASK = 0;
	private final int SEND_TASK = 1;
	private final int REQ_CODE_GALLERY = 100;
	private final int REQ_CODE_CATEGORY = 105;

	String marketerID;

	//data to be sent to server
	String marketerBrand;
	String itemName;
	String selectedCategory;
	Bitmap selectedPhoto;
	String briefInfo;

	EditText editText, itemNameText;
	TextView companyBrandName, categoryName;
	Button categoryBtn, imageLoad, productRegi;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_product_register);

		Intent marketerInfo = getIntent();
		marketerID = marketerInfo.getStringExtra("marketerID");

		companyBrandName = (TextView)findViewById(R.id.companyBrand);
		categoryName = (TextView)findViewById(R.id.selProduct);
		
		CommunicateDataTask receiveDataTask = new CommunicateDataTask();
		receiveDataTask.execute(RECEIVE_TASK);

		final ScrollView scrlView = (ScrollView)findViewById(R.id.productScrl);

		categoryBtn = (Button)findViewById(R.id.btnSelProduct);
		imageLoad = (Button)findViewById(R.id.btnGallery);
		productRegi = (Button)findViewById(R.id.btnRegiProductP);

		imageLoad.setOnClickListener(this);
		categoryBtn.setOnClickListener(this);
		productRegi.setOnClickListener(this);

		itemNameText = (EditText)findViewById(R.id.proNameText);
		editText = (EditText)findViewById(R.id.contentText);
		editText.setMovementMethod(new ScrollingMovementMethod());
		editText.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				scrlView.requestDisallowInterceptTouchEvent(true);
				return false;
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.product_register, menu);
		return true;
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch(v.getId()){

		case R.id.btnSelProduct:
			Intent categoryPage = new Intent(ProductRegister.this, ProductListview.class);
			startActivityForResult(categoryPage, REQ_CODE_CATEGORY);
			break;

		case R.id.btnGallery:
			Intent gallery = new Intent(Intent.ACTION_GET_CONTENT);
			gallery.setType("image/*");
			gallery.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivityForResult(gallery, REQ_CODE_GALLERY);
			break;

		case R.id.btnRegiProductP:
			briefInfo = editText.getText().toString();
			itemName = itemNameText.getText().toString();
			//send marketerID to server
			CommunicateDataTask sendDataTask = new CommunicateDataTask();
			sendDataTask.execute(SEND_TASK);
			break;
		}
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data){

		if(requestCode == REQ_CODE_GALLERY){

			if(resultCode == RESULT_OK){
				ImageView image = (ImageView)findViewById(R.id.productImage);
				Uri uri = data.getData();
				String path = uri.getPath();
				try {
					selectedPhoto = Images.Media.getBitmap(getContentResolver(), uri);//this image need to be sent to server
					image.setImageBitmap(selectedPhoto);
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		else if(requestCode == REQ_CODE_CATEGORY){
			if(resultCode == RESULT_OK){
				selectedCategory = data.getExtras().getString("data");
				categoryName.setText(selectedCategory);
			}
		}
	}

	private class CommunicateDataTask extends AsyncTask<Integer, String, Void>{

		@Override
		protected Void doInBackground(Integer... params) {
			// TODO Auto-generated method stub
			if(params[0] == RECEIVE_TASK){
				marketerBrand = "";
				try {
					URL url = new URL("http://192.168.43.64:8080/Weening11evenServer/CommunicateServlet");
					URLConnection connection = url.openConnection();

					//send ID to server
					connection.setDoOutput(true);
					OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
					out.write("For Brand/" + marketerID);
					out.close();

					//receive result of login from server
					BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
					marketerBrand = in.readLine();
					in.close();
				} catch (MalformedURLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				publishProgress(marketerBrand);
			}
			else if(params[0] == SEND_TASK){
				try {
					URL url = new URL("http://192.168.43.64:8080/Weening11evenServer/CommunicateServlet");
					URLConnection connection = url.openConnection();
					//byte[] imageByte = bitmapToByteArray(selectedPhoto);
					//String imageString = new String(imageByte, 0, imageByte.length);

					//send data to server
					connection.setDoOutput(true);
					OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
					out.write("For Register Product/" + itemName + "/" + briefInfo + "/" + selectedCategory + "/" + marketerBrand);
					out.close();
					
					//receive result of register from server
					String registerResult = "";
					BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
					registerResult = in.readLine();
					in.close();
					
					finishRegister();
				} catch (MalformedURLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			return null;
		}

		@Override
		protected void onProgressUpdate(String... values) {
			// TODO Auto-generated method stub
			super.onProgressUpdate(values);
			companyBrandName.setText(values[0]);
		}
	}
	public void finishRegister(){
		Intent goMarketerPage = new Intent(ProductRegister.this, MarketerPage.class);
		startActivity(goMarketerPage);
	}
	/*public byte[] bitmapToByteArray(Bitmap bitmap){
		ByteArrayOutputStream stream = new ByteArrayOutputStream();
		bitmap.compress(CompressFormat.PNG, 100, stream);
		byte[] byteArray = stream.toByteArray();
		return byteArray;
	}*/

}


